package com.eascs.partner.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.partner.dao.JxsPartnerDao;
import com.eascs.partner.entity.DealerPartnerEntity;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class JxsPartnerService {
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	JxsPartnerDao jxsPartnerDao;
	@Reference
	WorkFlowService workFlowService;

	public DealerPartnerEntity getEntityById(String id) {
		return jxsPartnerDao.getById(DealerPartnerEntity.class, id);
	}
	
    public ModelResult<Boolean> startUp(String jxsPartnerId) {
		try {
			DealerPartnerEntity partner = jxsPartnerDao.queryJxsPartnerEntityById(jxsPartnerId);
			WFRequestParam param = new WFRequestParam();
			param.setReferId(jxsPartnerId);//主键id
			param.setReferCode(partner.getPatternCode());//合作方code
			param.setReferUrl("/jxsPartner/rest/view_flow");//详情页面
			param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
			param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_JXS_PARTNERS_AUDIT_BP));//对应流程
			param.setProcessVersion("v1");
			User user = UserHolder.getUser();
			param.setAppliedby(user.getNo());
			param.setAppliedbyName(user.getCname());
			param.setOrgNo(partner.getOrgId());
			param.setAppliedDes("一批经销商渠道名称：" + partner.getBusinessLicenseName() + ", 经办人：" + user.getCname());

			/*if(StringUtil.isNotBlank(user.getOrg()) && user.getOrg().equals("1")) {
				List<String> list = new ArrayList<>();
				list.add("jxssqsp");
				param.setExcludeNodeCodeList(list);
			}*/
			logger.info("启动一批经销商合作方申请，参数有合作方id：【{}】，一批经销商合作方编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】", jxsPartnerId, partner.getPatternCode(), ProcessTemplate.SYSTEM_MODULE_O2O, param.getProcessType(),partner.getOrgId());
			ModelResult<Boolean> modelResult = workFlowService.instance(param);
			if (modelResult.isSuccess() && modelResult.getModel()) {
				jxsPartnerDao.processJxsPartnerStart(jxsPartnerId);
			} else {
				logger.error("启动一批经销商合作方申请失败，一批经销商合作方id：【{}】，错误信息{}", jxsPartnerId, modelResult.getErrMsg());
			}
			return modelResult;
		} catch (Exception e) {
			logger.error("启动一批经销商合作方申请失败，一批经销商合作方id：【{}】，错误：{}，", jxsPartnerId, e.getMessage());
			return new ModelResult<Boolean>("partner error", "启动一批经销商合作方申请失败");
		}
	}
	
}
